package com.ibm.cps.sql.expression.json;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.sql.expression.CalculationNode;
import com.ibm.cps.sql.expression.ValueExpression;
import com.ibm.cps.sql.expression.CalculationNode.Operator;

public class CalculationNodeDeserializer extends JsonDeserializer<CalculationNode>{

	@Override
	public CalculationNode deserialize(JsonParser jp,
			DeserializationContext arg1) throws IOException,
			JsonProcessingException {
		try {
			ObjectMapper mapper = (ObjectMapper) jp.getCodec();  
			ObjectNode root = (ObjectNode) mapper.readTree(jp);
			String operator = root.get("operator").asText();
			Operator op = Operator.valueOf(operator);
			String leftOperandType = root.get("leftOperandType").asText();
			String leftOperand = root.get("leftOperand").toString();
			String rightOperandType = root.get("rightOperandType").asText();
			String rightOperand = root.get("rightOperand").toString();
			ValueExpression left = (ValueExpression)mapper.readValue(leftOperand, Class.forName(leftOperandType));
			ValueExpression right = (ValueExpression)mapper.readValue(rightOperand, Class.forName(rightOperandType));
			return new CalculationNode(op, left, right);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
	}
	
}
